package com.jqh.openglesdemo.shader;

import android.content.Context;
import android.opengl.GLES20;
import android.util.Log;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

public class JqhShaderUtils {
    private static final String TAG = "JqhShaderUtils";

    public static String getRawResource(Context context , int rawId) {
        InputStream inputStream = context.getResources().openRawResource(rawId);
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuffer sb = new StringBuffer();
        String line ;
        try {

            while((line = reader.readLine()) != null) {
                sb.append(line).append("\n");
            }
            reader.close();
        }catch (Exception e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    private static int loadShader(int shaderType, String source){
        // 1 创建着色器Shader
        int shader = GLES20.glCreateShader(shaderType);
        if (shader != 0) {
            //  2 加载shader并编译
            GLES20.glShaderSource(shader, source);
            GLES20.glCompileShader(shader);

            //3  验证脚本编译代码是否有错误
            int[] compile = new int[1];
            GLES20.glGetShaderiv(shader, GLES20.GL_COMPILE_STATUS, compile, 0);
            if (compile[0] != GLES20.GL_TRUE) {
                Log.d(TAG, "shader compile error");
                GLES20.glDeleteShader(shader);
                shader = 0;
            }
            return shader;
        } else {
            return 0;
        }
    }

    public static int createProgram(String vertexSource, String fragmentSource) {
        int vertexShader = loadShader(GLES20.GL_VERTEX_SHADER, vertexSource);
        int fragmentShader = loadShader(GLES20.GL_FRAGMENT_SHADER, fragmentSource);

        if (vertexShader !=0 && fragmentShader != 0) {
            // 4 创建一个渲染程序
            int program = GLES20.glCreateProgram();
            // 5 将着色器添加到渲染程序中
            GLES20.glAttachShader(program, vertexShader);
            GLES20.glAttachShader(program, fragmentShader);
            // 6 链接源程序
            GLES20.glLinkProgram(program);
            return program;
        }
        return 0;
    }
}
